package com.blue.firecat.controller;

import com.alibaba.fastjson.JSON;
import com.blue.firecat.contants.Contants;
import com.blue.firecat.contants.Result;
import com.blue.firecat.entity.Note;
import com.blue.firecat.entity.Trade;
import com.blue.firecat.serivce.NoteService;
import com.blue.firecat.serivce.TradeService;
import com.blue.firecat.utils.controller.BaseController;
import com.blue.firecat.utils.excel.ExportExcel;
import com.blue.firecat.vo.TradeVo;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * @描述
 * @时间 2017/6/23 22:27
 * @作者 肖亦鸣
 */
@Controller
@RequestMapping("trade")
public class TradeController extends BaseController {
    private static Logger logger = LogManager.getLogger(TradeController.class.getName());
    @Autowired
    TradeService tradeService;
    @Autowired
    NoteService noteService;

    /**
     * 增加交易 (打手申请)
     *
     * @param trade
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addTrade", produces = {"text/json;charset=UTF-8"})
    public String addTrade(Trade trade) {
        logger.info("trade:{}", JSON.toJSONString(trade));
        Result<Trade> result = tradeService.insertSelective(getUserBySession(), trade);
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 交易列表
     *
     * @param tradeVo
     * @return
     */
    @RequestMapping("tradeList")
    public String tradeList(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<List<Trade>> result = tradeService.selectByExample(tradeVo, getUserBySession());
        request.setAttribute(Contants.TRADES, result.getData());
        request.setAttribute(Contants.OBJECT, tradeVo);
        logger.info("result:{}", JSON.toJSONString(result));
        return "trade-list";
    }

    /**
     * 是否同意 指派单
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "tradeAgree", produces = {"text/json;harset=UTF-8"})
    public String tradeAgree(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.tradeAgree(getUserBySession(), tradeVo);
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 审核通过
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setTradeWork", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String setTradeWork(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.setTradeWork(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 审核不通过
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setTradeNotPass", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String setTradeNotPass(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.setTradeNotPass(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 删除交易
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delTrade", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String delTrade(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.deleteByPrimaryKey(tradeVo.getTradeId());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 交易列表
     *
     * @param tradeVo
     * @return
     */
    @RequestMapping("tradeCommit")
    public String tradeCommit(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        request.setAttribute(Contants.OBJECT, tradeVo);
        return "trade-commit";
    }

    /**
     * 上传图片
     *
     * @return
     */
    @RequestMapping("/uploadHeadPic")
    @ResponseBody
    public String uploadHeadPic(@RequestParam("file") MultipartFile file, TradeVo tradeVo) throws Exception {
        logger.info("uploadHeadPic...");
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        int length = Contants.PIC_SUFFIX.indexOf(suffix);
        if (length == -1) {
            throw new Exception("请上传允许格式的文件");
        }
        if (file.getSize() > Contants.PIC_SIZE) {
            throw new Exception("您上传的文件大小已经超出范围");
        }

        String fileNameNew = new Date().getTime() + "." + suffix;
        Result<String> result = tradeService.addPics(fileNameNew, tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        if (result.isFail()) {
            return result.getMessage();
        }
        try {
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "p";
            String realPath = request.getSession().getServletContext().getRealPath("/");
            String realPathPhoto = realPath.substring(0, realPath.length() - 1) + "p";
            File destFile = new File(realPathPhoto + Contants.PIC_PATH);
            if (!destFile.exists()) {
                destFile.mkdirs();
            }

            File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
            logger.info(destFile.getAbsoluteFile() + "/" + fileNameNew);
            logger.info(basePath + Contants.PIC_PATH + fileNameNew);
            file.transferTo(f);
            f.createNewFile();
        } catch (Exception e) {
            throw e;
        }
        return "";
    }

    /**
     * 订单异常(登陆不上)
     *
     * @param tradeVo
     * @return
     */
    @RequestMapping(value = "tradeCommitError", method = RequestMethod.POST)
    public String tradeCommitError(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        //选上了才玩下点
        if (!"on".equals(tradeVo.getIsError())) {
            request.setAttribute(Contants.MESSAGE, "提交失败,请选上是否异常");
            request.setAttribute(Contants.OBJECT, tradeVo);
            return "trade-commit";
        }
        Result<Trade> result = tradeService.tradeCommitError(tradeVo, getUserBySession());
        request.setAttribute(Contants.MESSAGE, result.getMessage());
        logger.info("result:{}", JSON.toJSONString(result));
        return "trade-commit";
    }

    /**
     * 管理员 强制撤销
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "revokeTrade", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String revokeTrade(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.revokeTrade(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 打手打完了,验收通过
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkThrough", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String checkThrough(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.checkThrough(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 打手打完了,验收不通过
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setTradeCheckToNotPass", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String setTradeCheckToNotPass(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.setTradeCheckToNotPass(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 结算交易
     *
     * @param tradeVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "settlerTrade", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String settlerTrade(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.settlerTrade(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    @ResponseBody
    @RequestMapping(value = "settlerTradeAll", method = RequestMethod.POST, produces = {"text/json;charset=UTF-8"})
    public String settlerTradeAll(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<Trade> result = tradeService.settlerTradeAll(tradeVo, getUserBySession());
        logger.info("result:{}", JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    @RequestMapping("tradeShow")
    public String tradeShow(Long id) {
        Result<Trade> result = tradeService.selectByPrimaryKey(id, getUserBySession());
        request.setAttribute(Contants.OBJECT, result.getData());
        logger.info("result:{}", JSON.toJSONString(result));
        return "trade-show";
    }

    @RequestMapping("tradeCount")
    public String tradeCount(TradeVo tradeVo) {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        Result<List<Trade>> result = tradeService.tradeCount(tradeVo, getUserBySession());
        request.setAttribute(Contants.TRADES, result.getData());
        request.setAttribute(Contants.OBJECT, tradeVo);
        logger.info("result:{}", JSON.toJSONString(result));
        return "trade-count";
    }

    @RequestMapping("exportData")
    public String exportData(TradeVo tradeVo) throws Exception {
        logger.info("tradeVo:{}", JSON.toJSONString(tradeVo));
        String randomDate = String.valueOf(new Date().getTime());
        String filePath = ExportExcel.exportExcel(Contants.FILE_NAME + randomDate, Contants.FILE_NAME + randomDate, Contants.TRADE_EXPORT_HEADER, response,
                new ExportExcel.IDataWriteCallBack() {
                    @Override
                    public void writeData(WritableSheet sheet, WritableWorkbook wwb) throws Exception {
                        Result<List<Trade>> result = tradeService.tradeCount(tradeVo, getUserBySession());
                        logger.info("result:{}", JSON.toJSONString(result));
                        if (CollectionUtils.isEmpty(result.getData())) {
                            return;
                        }
                        jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.00"); // 设置数字格式
                        jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 设置表单格式

                        for (int i = 0; i < result.getData().size(); i++) {
                            int j = 0;
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getId() + ""));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getOrderId() + ""));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getUserId() + ""));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getUserName()));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getGameName()));
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getServiceArea()));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getContent()));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getCreateTimeString()));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getStatusString()));//
                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getRemark()));//
//                            sheet.addCell(new Label(j++, i + 1, result.getData().get(i).getSettlePrice() + ""));
                            sheet.addCell(new jxl.write.Number(j++, i + 1, result.getData().get(i).getSettlePrice().longValue(), wcfN));// 格式化数值
                        }
                    }
                });
        InputStream is = new FileInputStream(new File(filePath));
        OutputStream os = response.getOutputStream();
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + Contants.FILE_NAME + "trade" + randomDate + ".xlsx");
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (Exception e) {
            logger.info("exportData error:{}", e);
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        //  返回值要注意，要不然就出现下面这句错误！
        //java+getOutputStream() has already been called for this response
        return null;
    }

    /**
     * 跳转到 增加笔记界面
     *
     * @param note
     * @return
     */
    @RequestMapping(value = "nodeModify")
    public String nodeModify(Note note) {
        logger.info("note:{}", JSON.toJSONString(note));
        Note getNote = noteService.getByOrderId(note.getOrderId());
        if (getNote == null) {
            getNote = note;
        }
        request.setAttribute(Contants.OBJECT, getNote);
        return "note-commit";
    }

    /**
     * 增加笔记
     *
     * @param note
     * @return
     */
    @RequestMapping(value = "nodeCommit")
    public String nodeCommit(Note note) {
        logger.info("note:{}", JSON.toJSONString(note));
        int i = noteService.updateByOrderId(note);
        request.setAttribute(Contants.OBJECT, note);
        if (i == 1) {
            request.setAttribute(Contants.MESSAGE, "操作成功");
        }
        return "note-commit";
    }

}
